/*
 * @(#)MaintUserDelegationAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.user.web;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.dcivision.alert.bean.MtmUpdateAlertRecipient;
import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.alert.bean.UpdateAlertType;
import com.dcivision.alert.core.AlertManager;
import com.dcivision.alert.dao.UpdateAlertDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemFunctionConstant;
import com.dcivision.framework.Utility;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.AbstractMaintAction;
import com.dcivision.user.bean.UserDelegation;
import com.dcivision.user.dao.MtmUserGroupUserRoleDAObject;
import com.dcivision.user.dao.MtmUserRecordUserGroupDAObject;
import com.dcivision.user.dao.MtmUserRecordUserRoleDAObject;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRoleDAObject;

/**
  MaintUserDelegationAction.java

  This class is for maint user role.

    @author          Angus Shiu
    @company         DCIVision Limited
    @creation date   24/03/2003
    @version         $Revision: 1.11.4.2 $
*/

public class MaintUserDelegationAction extends AbstractMaintAction {

  public static final String REVISION = "$Revision: 1.11.4.2 $";

  protected Log log = LogFactory.getLog(this.getClass().getName());
  
  public MaintUserDelegationAction() {
    super();
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  
  public String getMajorDAOClassName() {
    return("com.dcivision.user.dao.UserDelegationDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  
  public String getFunctionCode() {
    return(SystemFunctionConstant.WORKFLOW_DELEGATION + "||" +SystemFunctionConstant.WORKFLOW_TASK);
  }

  /**
   * clearUniqueFields
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  
  public void clearUniqueFields(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
//    MaintUserDelegationForm userDelegationForm = (MaintUserDelegationForm)form;
    //userDelegationForm.setTargetObjectID(null);
  }

  /**
   * selectRecord
   *
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  
  public void selectRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    super.selectRecord(mapping, form, request, response);
  }

  
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    AbstractActionForm maintForm = (AbstractActionForm)form;
    String opMode = (maintForm != null) ? maintForm.getOpMode() : request.getParameter("opMode"); //maintForm.getOpMode();
//    String navMode = (maintForm != null) ? maintForm.getNavMode() : request.getParameter("navMode"); //maintForm.getNavMode();
    
    MaintUserDelegationForm delegationForm = (MaintUserDelegationForm) maintForm;
    log.info("��120��"+delegationForm.getSourceUserID());
    UserRoleDAObject roleDAO = (UserRoleDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.UserRoleDAObject");
    UserGroupDAObject groupDAO = (UserGroupDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.UserGroupDAObject");
    List objectList = new ArrayList();
    
    if (GlobalConstant.SUBJECT_TYPE_GROUP.equals(delegationForm.getTargetObjectType()) ) {
      objectList = groupDAO.getFullList();
    } else if (GlobalConstant.SUBJECT_TYPE_ROLE.equals(delegationForm.getTargetObjectType()) ) {
      objectList = roleDAO.getFullList();
    }
    
    request.setAttribute("objectList", objectList);

    if (GlobalConstant.OP_MODE_REFRESH.equals(opMode)) {
      // Set the function code for current action.
      ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
      if (forward != null) {
        return forward;
      }
      //refreshFormData(mapping, maintForm, request, response);
      delegationForm.setTargetObjectID(null);
      return mapping.findForward(GlobalConstant.NAV_MODE_REFRESH);
    }
    else {
      return super.execute(mapping, form, request, response);
    }
  }
  
  
  public void insertRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  //  log.debug("hello");
    super.insertRecord(mapping, form, request, response);
  //  log.debug("hello1");
    
    this.notifyTargetActor(form, request);
  }

  
  public void updateRecord(ActionMapping mapping, AbstractActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
  //  log.debug("hello3");
    super.updateRecord(mapping, form, request, response);
  //  log.debug("hello4");
    
    notifyTargetActor(form, request);
  }
  
  // Function that change original system alert to be inactive if exists. 
  private void deleteOriginalSystemNotifyByObjectTypeAndObjectID(String objectType, Integer objectID, HttpServletRequest request) throws ApplicationException {
    SessionContainer sessionCon = this.getSessionContainer(request);
    Connection conn = this.getConnection(request);
    UpdateAlertDAObject updateAlertDao=new UpdateAlertDAObject(sessionCon, conn);
    UpdateAlert originalUpdateAlert = (UpdateAlert) updateAlertDao.getByObjectTypeObjectID(objectType, objectID);
    
    // If original record is not empty, change it into inactive status.
    if (!Utility.isEmpty(originalUpdateAlert)) {
      updateAlertDao.updateStatus(originalUpdateAlert);
    }
  }
  
  private void notifyTargetActor(AbstractActionForm form, HttpServletRequest request) throws ApplicationException {
    MaintUserDelegationForm delegationForm = (MaintUserDelegationForm) form;
    UserDelegation delegation = (UserDelegation) delegationForm.getFormData();
    
    // Change original system alert record to be inactive before add new.---------------------------
    if(!request.getParameter("opMode").equals(GlobalConstant.OP_MODE_INSERT)){
      this.deleteOriginalSystemNotifyByObjectTypeAndObjectID(UpdateAlert.DELEGATION_TYPE, delegation.getID(), request);
    }
    
    log.debug("alertByEmail: "+delegationForm.getAlertByEmail());
    log.debug("alertBySystem: "+delegationForm.getAlertBySystem());
    
    if (UpdateAlert.EMAIL_NOTIFICATION.equals(delegationForm.getAlertByEmail()) || UpdateAlert.SYSTEM_NOTIFICATION.equals(delegationForm.getAlertBySystem())) {
      List recipientList = this.getUserRecordListByTargetObjectTypeAndID(delegation.getTargetObjectType(), delegation.getTargetObjectID(), request); 
      log.debug("recipientList: "+recipientList);
      
      SessionContainer sessionCon = this.getSessionContainer(request);
      Connection conn = this.getConnection(request);
      if (UpdateAlert.EMAIL_NOTIFICATION.equals(delegationForm.getAlertByEmail())) {
        AlertManager am = new AlertManager(sessionCon, conn);
        am.createWorkflowEmailNotification(delegation.getID(), UpdateAlert.DELEGATION_TYPE, UpdateAlert.DELEGATION_ACTION, recipientList);
      } 
      if (UpdateAlert.SYSTEM_NOTIFICATION.equals(delegationForm.getAlertBySystem())) {
        AlertManager am = new AlertManager(sessionCon, conn);
        
        UpdateAlert updateAlert = new UpdateAlert();
        updateAlert.setMessage(null);
        updateAlert.setObjectType(UpdateAlert.DELEGATION_TYPE);
        updateAlert.setObjectID(delegation.getID());
        updateAlert.setDueDate(null);
        
        UpdateAlertType[] updateAlertTypes = new UpdateAlertType[1];
        UpdateAlertType updateAlertType = new UpdateAlertType();
        updateAlertType.setUpdateAlertID(updateAlert.getID());
        updateAlertType.setActionType(UpdateAlert.DELEGATION_ACTION);
        updateAlertType.setNotifyWay(UpdateAlert.SYSTEM_NOTIFICATION);
        updateAlertType.setMessage(updateAlert.getMessage());
        updateAlertType.setDueDate(updateAlert.getDueDate());
        updateAlertTypes[0] = updateAlertType;
        
        MtmUpdateAlertRecipient[] updateRecipient = new MtmUpdateAlertRecipient[1];
        updateRecipient =  am.getRecipient(Utility.getStringArray(recipientList), new String[0], new String[0]);
        updateAlert =am.createUpdateAlert(updateAlert, updateAlertTypes, updateRecipient, null, "", null, "", sessionCon.getUserRecordID(), recipientList);
      }
    }
  }
  
  private List getUserRecordListByTargetObjectTypeAndID(String targetObjectType, Integer targetObjectID, HttpServletRequest request) throws ApplicationException {
    List userList = new ArrayList();
    try {
      if (GlobalConstant.SUBJECT_TYPE_USER.equals(targetObjectType)) {
        userList.add(targetObjectID);
      } else if (GlobalConstant.SUBJECT_TYPE_GROUP.equals(targetObjectType)) {
        MtmUserRecordUserGroupDAObject mtmUserRecordUserGroupDAO = (MtmUserRecordUserGroupDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.MtmUserRecordUserGroupDAObject");
        MtmUserGroupUserRoleDAObject mtmUserGroupUserRoleDAO = (MtmUserGroupUserRoleDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.MtmUserGroupUserRoleDAObject");
        MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAO = (MtmUserRecordUserRoleDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.MtmUserRecordUserRoleDAObject");
        
        Integer groupID = targetObjectID;
        List groupAry = new ArrayList();
        List roleList = new ArrayList();//add by dick ;fix bug 2453
        groupAry.add(groupID);
        List userRecordGroupList = mtmUserRecordUserGroupDAO.getListByUserGroupAry(groupAry);
        userList = Utility.getPropertyList(userRecordGroupList, "userRecordID");
        
        List userGroupRoleList = mtmUserGroupUserRoleDAO.getListByUserGroupAry(groupAry);
        //List roleList = Utility.getPropertyList(userGroupRoleList, "userRoleID");
        roleList = Utility.getPropertyList(userGroupRoleList, "userRoleID");//add by dick ;fix bug 2453
        if(!Utility.isEmpty(roleList)) {
          List userRecordRoleList = mtmUserRecordUserRoleDAO.getListByUserRoleAry(roleList);
          userList.addAll(Utility.getPropertyList(userRecordRoleList, "userRecordID"));
        }
        userList = Utility.removeDuplicate(userList);
      } else if (GlobalConstant.SUBJECT_TYPE_ROLE.equals(targetObjectType)) {
        MtmUserRecordUserRoleDAObject mtmUserRecordUserRoleDAO = (MtmUserRecordUserRoleDAObject) this.getDAObjectByClassName(request, "com.dcivision.user.dao.MtmUserRecordUserRoleDAObject");
        
        Integer roleID = targetObjectID;
        List roleAry = new ArrayList();
        roleAry.add(roleID);
        List userRecordRoleList = mtmUserRecordUserRoleDAO.getListByUserRoleAry(roleAry);
        userList = Utility.getPropertyList(userRecordRoleList, "userRecordID");
      }
    } catch (IllegalAccessException e) {
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } catch (java.lang.reflect.InvocationTargetException e) {
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } catch (NoSuchMethodException e) {
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    }
    
    return userList;
  }

}
